package sky.cin.framework.sfoc.core.common.utils;

import sky.cin.framework.sfoc.core.annotations.beans.Component;

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtils<T> {
    
    public static String getBeanName(Class<?> clazz) {
        String value = "";
        if (BeanUtils.isAnnotationPresent(clazz, Component.class)) {
            value = BeanUtils.getAnnotation(clazz, Component.class).value();
        }
        if ("".equals(value)) {
            String className = clazz.getName();
            int index = className.lastIndexOf(".");
            char[] chars = className.substring(index + 1) .toCharArray();
            chars[0] = (char) (chars[0] + 32);
            value = new String(chars);
        }
        return value;
    }
    
    public static<T> boolean isAnnotationPresent(Object obj, Class<T> target) {
        T annotation = getAnnotation(obj, target);
        return annotation != null;
    }
    
    public static<T> T getAnnotation(Object obj, Class<T> target) {
        Annotation[] annotations = null;
        if (obj instanceof Class) {
            annotations = ((Class<?>) obj).getAnnotations();
        } else if (obj instanceof Method) {
            annotations = ((Method) obj).getAnnotations();
        } else if (obj instanceof Field) {
            annotations = ((Field) obj).getAnnotations();
        } else if (obj instanceof Annotation) {
            annotations = new Annotation[]{(Annotation) obj};
        }
        if (annotations == null) {
            return null;
        }
        for (Annotation annotation : annotations) {
            Class<? extends Annotation> annoClazz = annotation.annotationType();
            if (annoClazz != Retention.class &&
                annoClazz != Target.class &&
                annoClazz != Inherited.class &&
                annoClazz != Documented.class
            ) {
                if (annoClazz == target) {
                    return (T) annotation;
                }
                T result = getAnnotation(annoClazz, target);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
    
}
